package work.vcloud.baseinfo.controller.recruit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import work.vcloud.baseinfo.exception.BaseException;
import work.vcloud.baseinfo.service.intfc.BatchInsertService;
import work.vcloud.baseinfo.utils.ImportExcelUtil;
import work.vcloud.frame.controller.BaseController;
import work.vcloud.frame.dao.OpenDao;
import work.vcloud.frame.vo.OutputVo;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 招生名单管理
 */
@RestController
@Scope("prototype")
public class RecruitStudentController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    OpenDao openDao;

    @Resource
    BatchInsertService batchInsertService;

    /**
     * 添加录取学生
     *
     * @return
     */
    @RequestMapping("/recruitStudent/addRecruitStudent")
    public OutputVo addRecruitStudent() {
        try {
            Map<String, Object> map = getParameterMap();
            map.remove("page");

            List<Map<String, Object>> dataList = Collections.singletonList(map);
            fillData(map, dataList);
            map = dataList.get(0);

            map.put("sqlMapId", "recruitStudent.addRecruitStudent");
            openDao.insert(map);

            return output("0000");
        } catch (BaseException e) {
            e.printStackTrace();
            return output("9999", e.getMessage(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return output("9999", "", e.getMessage().toString());
        }
    }

    /**
     * 导入招生名单
     *
     * @param multipartFile
     * @param formData
     * @return
     */
    @RequestMapping("/recruitStudent/import")
    public OutputVo teacherImportUpdate(@RequestParam("upfile") MultipartFile multipartFile, @RequestParam("formData") String formData) {
        try {
            Map<String, Object> map = getParameterMap();
            map.remove("page");
            if (multipartFile.isEmpty()) {
                throw new BaseException("文件不存在！");
            }
            JSONObject jsonData = (JSONObject) JSON.parse(formData);

            List colList = new ArrayList();
            fillColList(colList);

            // 获取excel 数据
            List<Map<String, Object>> dataList = new ImportExcelUtil().readExcel(multipartFile.getInputStream(), colList);
            if (dataList.size() > 0 && dataList.get(0).size() != colList.size()) {
                System.out.println("Excel表格中有多出的列！");
            }

            System.out.println(dataList);

            fillData(map, dataList);
            batchInsertService.batchInsert("recruitStudent.addRecruitStudentBatch", dataList, map);

            return output("0000");
        } catch (BaseException e) {
            e.printStackTrace();
            return output("9999", e.getMessage(), e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return output("9999", "", e.getMessage().toString());
        }
    }

    /**
     * 填充数据（fk_grade fk_sex fk_major）
     *
     * @param map
     * @param dataList
     * @throws Exception
     */
    private void fillData(Map<String, Object> map, List<Map<String, Object>> dataList) throws Exception {
        // 单位
        Map userInfo = (Map) map.get("userInfo");
        map.put("fk_unit", userInfo.get("unitId"));

        // 查询所有年级
        //map.put("sqlMapId", "grade.select");
        map.put("sqlMapId", "grade.selectSchoolGrade");
        List<Map<String, Object>> gradeList = openDao.queryForList(map);
        Map<Object, Map<String, Object>> name_gradeMap = gradeList.stream().collect(Collectors.toMap(m -> m.get("name"), m -> m));

        // 性别
        Map<String, String> sexMap = new HashMap();
        sexMap.put("男", "0000000SEX2010042716554107870639942");
        sexMap.put("女", "0000000SEX2010042716554109392196554");

        // 查询所有专业
        map.put("sqlMapId", "major.select");
        List<Map<String, Object>> majorList = openDao.queryForList(map);
        Map<Object, Map<String, Object>> name_majorMap = majorList.stream().collect(Collectors.toMap(m -> m.get("code") + "&" + m.get("fk_grade"), m -> m));

        // 补充数据
        for (int i = 0; i < dataList.size(); i++) {
            Map<String, Object> stu = dataList.get(i);
            // 年级
            String gradeName = (String) stu.get("grade");
            Map<String, Object> gradeMap = name_gradeMap.get(gradeName);
            if (gradeMap == null) {
                //System.out.println("没有找到对应的年级！");
                throw new BaseException("没有找到对应的年级：" + gradeName);
            }
            String fk_grade = (String) gradeMap.get("id");
            stu.put("fk_grade", fk_grade);
            // 性别
            String sex = (String) stu.get("sex");
            String fk_sex = sexMap.get(sex);
            stu.put("fk_sex", fk_sex);
            // 专业
            Object major_code = stu.get("major_code");
            Map<String, Object> majorMap = name_majorMap.get(major_code + "&" + fk_grade);
            if (majorMap == null) {
                //System.out.println("没有找到对应的专业！");
                throw new BaseException("没有找到对应的专业：" + major_code);
            }
            Object fk_major = majorMap.get("id");
            stu.put("fk_major", fk_major);
        }
    }

    /**
     * 填充excel表头映射数据
     *
     * @param colList
     */
    private void fillColList(List colList) {
        Map tMap = new HashMap();
        tMap = new HashMap();
        tMap.put("name", "年级");
        tMap.put("col", "grade");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "学生类别");
        tMap.put("col", "student_type");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "招生类别");
        tMap.put("col", "recruit_type");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "计划性质");
        tMap.put("col", "plan_nature");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "序号");
        tMap.put("col", "ord");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "考生登记号");
        tMap.put("col", "examinee_register");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "姓名");
        tMap.put("col", "name");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "性别");
        tMap.put("col", "sex");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "学制");
        tMap.put("col", "school_system");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "录取总分");
        tMap.put("col", "score");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "报考区县");
        tMap.put("col", "district");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "毕业学校");
        tMap.put("col", "from_school");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "招生代码");
        tMap.put("col", "recruit_code");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "专业目录代码");
        tMap.put("col", "major_code");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "身份证号");
        tMap.put("col", "id_no");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "家庭住址");
        tMap.put("col", "address");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "联系电话");
        tMap.put("col", "phone");
        colList.add(tMap);
        tMap = new HashMap();
        tMap.put("name", "邮政编码");
        tMap.put("col", "mail");
        colList.add(tMap);
    }


}
